<template>
    <div class="maintain-container">
        <!-- 场地类型和日期选择区域 -->
        <div class="filter-section">
            <div class="filter-row">
                <el-form :inline="true" class="type-select">
                    <el-form-item label="场地类型" class="no-margin">
                        <el-select v-model="selectedVenueTypeId" placeholder="请选择场地类型" @change="handleVenueTypeChange"
                            style="width: 180px;">
                            <el-option v-for="type in venueTypes" :key="type.id" :label="type.name"
                                :value="type.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>

                <div class="date-section">
                    <div class="date-scroll-wrapper">
                        <div class="date-scroll-container" ref="dateScrollContainer">
                            <div class="date-scroll-content" :style="{ transform: `translateX(${scrollPosition}px)` }">
                                <div v-for="(day, index) in dateDays" :key="index" class="day-item"
                                    :class="{ 'active': selectedDateIndex === index }" @click="selectDate(index)">
                                    <div class="day-name">{{ day.weekday }}</div>
                                    <div class="day-date">{{ day.date }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 场地时间表格区域 -->
        <div class="table-container">
            <!-- 时间轴 -->
            <div class="time-axis" ref="timeAxis">
                <div style="height: 10px;"></div>
                <div v-for="(time, index) in timeSlots" :key="index" class="time-cell">
                    {{ time }}
                </div>
            </div>

            <!-- 场地表格 -->
            <div class="venue-table" ref="venueTable" @scroll="handleVenueScroll">
                <div class="venue-header">
                    <div v-for="venue in displayVenues" :key="venue.id" class="venue-column">
                        {{ venue.name }}
                    </div>
                </div>
                <div class="venue-body">
                    <div v-for="(timeSlot, timeIndex) in timeSlots.slice(0, timeSlots.length - 1)" :key="timeIndex"
                        class="venue-row">
                        <div v-for="venue in displayVenues" :key="`${timeSlot}-${venue.id}`" class="venue-cell"
                            :class="getCellClass(timeIndex, venue.id)" @click="handleCellClick(timeIndex, venue.id)">
                            <span class="cell-status">{{ getCellStatus(timeIndex, venue.id) }}</span>
                        </div>
                    </div>
                    <div v-for="venue in displayVenues" :key="`spacer-${venue.id}`" style="height: 5px;">
                    </div>
                </div>
            </div>
        </div>

        <!-- 图例说明 -->
        <div class="legend">
            <div class="legend-item">
                <div class="color-box normal"></div>
                <span>正常</span>
            </div>
            <div class="legend-item">
                <div class="color-box reserved"></div>
                <span>已被用户预约</span>
            </div>
            <div class="legend-item">
                <div class="color-box maintain"></div>
                <span>维护中</span>
            </div>
        </div>

        <!-- 新增维护记录分页展示 -->
        <div class="form-section maintenance-records">
            <h2>维护记录</h2>
            <!-- 筛选表单和新增按钮 -->
            <el-form :inline="true" :model="maintenanceQuery" class="maintenance-filter" style="margin-bottom: 16px;">
                <el-form-item label="开始时间">
                    <el-date-picker v-model="maintenanceQuery.start_time" type="date" placeholder="开始日期"
                        style="width: 140px;" />
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker v-model="maintenanceQuery.end_time" type="date" placeholder="结束日期"
                        style="width: 140px;" />
                </el-form-item>
                <el-form-item label="原因">
                    <el-input v-model="maintenanceQuery.reason" placeholder="输入原因" style="width: 150px;" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchMaintenances(1)">筛选</el-button>
                    <el-button @click="resetMaintenanceQuery">重置</el-button>
                </el-form-item>
                <el-form-item style="float:right;">
                    <el-button type="success" @click="showAddDialog = true">新增维护</el-button>
                </el-form-item>
            </el-form>
            <!-- 新增维护记录弹窗 -->
            <el-dialog v-model="showAddDialog" title="新增维护记录" width="320px" class="custom-maintain-dialog">
                <el-form :model="addForm" label-width="80px" style="width:100%;">
                    <el-form-item label="场地">
                        <el-select v-model="addForm.venue_id" placeholder="请选择场地" style="width:100%;">
                            <el-option v-for="venue in venues" :key="venue.id" :value="venue.id"
                                :label="getVenueInfo(venue.id)" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="开始时间">
                        <el-date-picker v-model="addForm.start_time" type="datetime" placeholder="选择开始时间"
                            style="width:100%;" :disabled-hours="disabledHours" :disabled-minutes="disabledMinutes"
                            :disabled-seconds="disabledSeconds" :show-now="false" />
                    </el-form-item>
                    <el-form-item label="结束时间">
                        <el-date-picker v-model="addForm.end_time" type="datetime" placeholder="选择结束时间"
                            style="width:100%;" :disabled-hours="disabledHours" :disabled-minutes="disabledMinutes"
                            :disabled-seconds="disabledSeconds" :show-now="false" />
                    </el-form-item>
                    <el-form-item label="原因">
                        <el-input v-model="addForm.reason" placeholder="请输入原因" style="width:100%;" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleAddMaintenance">确定</el-button>
                </template>
            </el-dialog>
            <!-- 编辑维护记录弹窗 -->
            <el-dialog v-model="showEditDialog" title="编辑维护记录" width="400px">
                <el-form :model="editForm" label-width="80px">
                    <el-form-item label="场地">
                        <span>{{ getVenueInfo(editForm.venue_id) }}</span>
                    </el-form-item>
                    <el-form-item label="开始时间">
                        <span>{{ editForm.start_time }}</span>
                    </el-form-item>
                    <el-form-item label="结束时间">
                        <span>{{ editForm.end_time }}</span>
                    </el-form-item>
                    <el-form-item label="原因">
                        <el-input v-model="editForm.reason" placeholder="请输入原因" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="showEditDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleUpdateMaintenance">确定</el-button>
                </template>
            </el-dialog>
            <!-- 表格和分页 -->
            <el-table :data="maintenanceList" style="width: 100%; margin-top: 20px;">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="admin_no" label="操作人工号" width="150" />
                <el-table-column prop="venue_id" label="场地信息" width="180">
                    <template #default="scope">
                        {{ getVenueInfo(scope.row.venue_id) }}
                    </template>
                </el-table-column>
                <el-table-column prop="start_time" label="开始时间" width="180">
                    <template #default="scope">
                        {{ scope.row.start_time }}
                    </template>
                </el-table-column>
                <el-table-column prop="end_time" label="结束时间" width="180">
                    <template #default="scope">
                        {{ scope.row.end_time }}
                    </template>
                </el-table-column>
                <el-table-column prop="reason" label="原因" width="200" />
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 16px; text-align: right;">
                <el-pagination background layout="prev, pager, next" :total="maintenanceTotal" :page-size="pageSize"
                    :current-page="currentPage" @current-change="handlePageChange" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useVenueStore } from '@/stores/venue'
import { apiFindVenueType } from '@/request/venueType'
import { apiFindVenue } from '@/request/venue'
import dayjs from 'dayjs'
import { apiFindMaintenance, apiCreateMaintenance, apiUpdateMaintenance, apiDeleteMaintenance } from '@/request/maintenance'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiFindReservation } from '@/request/reservation'
// 获取store实例
const venueStore = useVenueStore()

// 场地类型列表
const venueTypes = ref([])
// 场地列表
const venues = ref([])
// 选中的场地类型ID
const selectedVenueTypeId = ref(null)
// 日期选择相关
const dateDays = ref([])
const selectedDateIndex = ref(0)
const selectedFullDate = computed(() => dateDays.value[selectedDateIndex.value].fullDate)
const dateScrollContainer = ref(null)
const scrollPosition = ref(0)

// 表格滚动处理
const timeAxis = ref(null)
const venueTable = ref(null)

// 滑动相关变量
const translateX = ref(0)
const dateScrollContent = ref(null)

// 单元格状态数据 (用于存储每个单元格的状态)
const cellStatus = reactive(new Map())

// 显示添加维护记录的flag
const showAddDialog = ref(false)

// 预约记录列表
const reservationList = ref([])
const reservationMap = ref(new Map())


// 选择日期
const selectDate = async (index) => {
    selectedDateIndex.value = index
    const selectedDate = dateDays.value[index].fullDate.format('YYYY-MM-DD')

    // 清空单元格状态
    cellStatus.clear()

    // 获取当天的预约记录
    await FindReservation(selectedDate)

    // 过滤维护记录
    const filteredMaintenanceList = maintenanceList.value.filter(m =>
        dayjs(m.start_time).format('YYYY-MM-DD') === selectedDate
    )
    // console.log(filteredMaintenanceList);


    // 更新单元格状态
    initCellStatus(filteredMaintenanceList)
}

// 初始化单元格状态
const initCellStatus = (filteredMaintenanceList) => {
    // console.log(filteredMaintenanceList);

    timeSlots.value.forEach((timeSlot, timeIndex) => {
        venues.value.forEach(venue => {
            const key = `${timeIndex}-${venue.id}`
            let status = 'normal'

            const rez = reservationList.value.find(m =>
                m.venue_id === venue.id &&
                dayjs(m.start_time).hour() <= parseInt(timeSlot.split(':')[0]) &&
                dayjs(m.end_time).hour() > parseInt(timeSlot.split(':')[0])
            )
            if (rez) {
                status = 'reserved'
            }


            const maintenance = filteredMaintenanceList.find(m =>
                m.venue_id === venue.id &&
                dayjs(m.start_time).hour() <= parseInt(timeSlot.split(':')[0]) &&
                dayjs(m.end_time).hour() > parseInt(timeSlot.split(':')[0])
            )
            if (maintenance) {
                status = 'maintain'
            }
            cellStatus.set(key, status)
        })
    })
}



// 获取单元格类名
const getCellClass = (timeIndex, venueId) => {
    const key = `${timeIndex}-${venueId}`
    // console.log(key);

    return {
        'normal': cellStatus.get(key) === 'normal',
        // 'selected': cellStatus.get(key) === 'selected',
        'maintain': cellStatus.get(key) === 'maintain',
        'reserved': cellStatus.get(key) === 'reserved'
    }
}

// 获取单元格状态文本
const getCellStatus = (timeIndex, venueId) => {
    const key = `${timeIndex}-${venueId}`
    const statusMap = {
        'normal': '', // 正常状态不显示文字
        // 'selected': '已选择',
        'maintain': '维护中',
        'reserved': '被用户预定'
    }
    return statusMap[cellStatus.get(key)] || ''
}

// 单元格点击处理
const handleCellClick = (timeIndex, venueId) => {
    const key = `${timeIndex}-${venueId}`
    const currentStatus = cellStatus.get(key) || 'normal'

    if (currentStatus === 'maintain') {
        // 显示维护原因
        const maintenance = maintenanceList.value.find(m =>
            m.venue_id === venueId &&
            dayjs(m.start_time).hour() <= parseInt(timeSlots.value[timeIndex].split(':')[0]) &&
            dayjs(m.end_time).hour() > parseInt(timeSlots.value[timeIndex].split(':')[0])
        )
        if (maintenance) {
            ElMessageBox.alert(`维护原因: ${maintenance.reason}`, '维护信息', {
                confirmButtonText: '关闭',
                type: 'info',
            })
        }
    } else {

        // 弹出维护弹窗
        showAddDialog.value = true
        addForm.value.venue_id = venueId
        addForm.value.start_time = selectedFullDate.value.hour(parseInt(timeSlots.value[timeIndex].split(':')[0])).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
        addForm.value.end_time = selectedFullDate.value.hour(parseInt(timeSlots.value[timeIndex + 1].split(':')[0])).minute(0).second(0).format('YYYY-MM-DD HH:mm:ss')
    }
}



/////////////////////////////////////////////////////


onMounted(async () => {
    // 初始化日期为今天
    initDateDays()

    // 获取场地类型和场地数据
    await fetchVenueTypes()

    // 确保日期滚动容器已渲染
    nextTick(() => {
        if (dateScrollContent.value) {
            // 初始化滚动位置
            translateX.value = 0
        }
    })
    // 页面加载时获取第一页维护记录
    await fetchMaintenances(1)

    selectedDateIndex.value = 0
    selectDate(selectedDateIndex.value)

})

// 表格滚动处理
const handleVenueScroll = () => {
    timeAxis.value.scrollTop = venueTable.value.scrollTop
};

// 初始化日期数据
const initDateDays = () => {
    const today = dayjs()
    dateDays.value = Array.from({ length: 14 }, (_, i) => {
        const date = today.add(i, 'day')
        return {
            date: date.format('MM-DD'),
            weekday: i === 0 ? '今天' : ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.day()],
            fullDate: date
        }
    })
}

// 时间段列表 (7:00-23:00)
const timeSlots = ref([
    '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00',
    '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00',
    '21:00', '22:00', '23:00'
])

// 计算当前显示的场地
const displayVenues = computed(() => {
    if (!selectedVenueTypeId.value) return []
    return venues.value.filter(venue => venue.venueTypeId === selectedVenueTypeId.value)
})


// 获取场地类型列表
const fetchVenueTypes = async () => {
    // 检查store中是否已有数据
    if (venueStore.venueTypes && venueStore.venueTypes.length > 0) {
        venueTypes.value = venueStore.venueTypes
        if (venueTypes.value.length > 0) {
            selectedVenueTypeId.value = venueTypes.value[0].id
            await fetchVenues()
        }
        return
    }

    try {
        const res = await apiFindVenueType()
        const types = res.data.venue_types.map(type => ({
            id: type.id,
            name: type.name,
            pricePerHour: type.price_per_hour
        }))

        venueStore.setVenueTypes(types)
        venueTypes.value = types

        if (types.length > 0) {
            selectedVenueTypeId.value = types[0].id
            await fetchVenues()
        }
    } catch (error) {
        console.error('获取场地类型失败:', error)
    }
}

// 获取场地列表
const fetchVenues = async () => {
    if (!selectedVenueTypeId.value) return

    // 检查store中是否已有数据
    const storedVenues = venueStore.getVenuesByType(selectedVenueTypeId.value)
    if (storedVenues && storedVenues.length > 0) {
        venues.value = storedVenues
        return
    }

    try {
        const res = await apiFindVenue(selectedVenueTypeId.value)
        if (!res.data || !res.data.venues || res.data.venues.length === 0) {
            venues.value = []
            return
        }
        // console.log(res);

        const venueList = res.data.venues.map(venue => ({
            id: venue.id,
            number: venue.number,
            name: `${venue.number}号场地`,
            venueTypeId: venue.venue_type_id,
            pricePerHour: venueTypes.value.find(type => type.id === venue.venue_type_id).pricePerHour,
        }))

        venues.value = venueList
        venueStore.setVenues(venueList)
        // console.log('获取场地列表成功:', venues.value);

        // initCellStatus()
    } catch (error) {
        console.error('获取场地列表失败:', error)
        venues.value = []
    }
}

// 场地类型变更处理
const handleVenueTypeChange = async () => {
    venueStore.setCurrentVenueTypeId(selectedVenueTypeId.value)
    maintenanceQuery.value.venue_type_id = selectedVenueTypeId.value
    await fetchVenues()
    await fetchMaintenances(1)
    selectDate(0)
}

//////////////////////////////////////////////////////
// 维护记录相关
const maintenanceList = ref([])
const maintenanceTotal = ref(0)
const currentPage = ref(1)
const pageSize = 10

// 查询条件
const maintenanceQuery = ref({
    venue_type_id: 1,
    start_time: '',
    end_time: '',
    reason: ''
})

// 获取维护记录
const fetchMaintenances = async (page = 1) => {
    try {
        const data = {
            venue_type_id: maintenanceQuery.value.venue_type_id,
            start_time: maintenanceQuery.value.start_time,
            end_time: maintenanceQuery.value.end_time,
            reason: maintenanceQuery.value.reason,
            page: page,
            page_size: pageSize
        }

        if (data.start_time) {
            data.start_time = dayjs(data.start_time).format('YYYY-MM-DD')
        }
        if (data.end_time) {
            data.end_time = dayjs(data.end_time).format('YYYY-MM-DD')
        }

        const res = await apiFindMaintenance(data)
        res.data.maintenances.forEach(maintenance => {
            maintenance.start_time = dayjs(maintenance.start_time).format('YYYY-MM-DD HH:mm:ss')
            maintenance.end_time = dayjs(maintenance.end_time).format('YYYY-MM-DD HH:mm:ss')
        })
        maintenanceList.value = res.data.maintenances || []
        maintenanceTotal.value = res.data.total || 0
    } catch (e) {
        maintenanceList.value = []
        maintenanceTotal.value = 0
    }
}

// 新增维护记录
const createMaintenance = async (data) => {
    try {
        await apiCreateMaintenance(data)
        await fetchMaintenances(currentPage.value)
        selectDate(selectedDateIndex.value)

    } catch (e) {
        // 错误处理
    }
}

const handlePageChange = (page) => {
    currentPage.value = page
    fetchMaintenances(page)
}


const getVenueInfo = (venueId) => {
    if (!venueId) return "All Venues"
    const venue = venueStore.venues.find(v => v && v.id === venueId)
    if (!venue) return `Venue ID: ${venueId}`
    const venueType = venueStore.venueTypes.find(t => t.id === venue.venueTypeId)
    const typeName = venueType ? venueType.name : 'Unknown Type'
    return `${typeName} - ${venue.number}号场地`
}

const addForm = ref({
    venue_id: 0,
    start_time: '',
    end_time: '',
    reason: ''
})
// 新增维护记录弹窗提交
const handleAddMaintenance = async () => {
    if (!addForm.value.start_time || !addForm.value.end_time || !addForm.value.reason) {
        ElMessage.warning('请填写完整信息')
        return
    }
    const data = {
        venue_id: addForm.value.venue_id,
        start_time: addForm.value.start_time,
        end_time: addForm.value.end_time,
        reason: addForm.value.reason,
        rez_ids: []
    }
    if (data.start_time) {
        data.start_time = dayjs(data.start_time).format('YYYY-MM-DD HH:mm:ss')
    }
    if (data.end_time) {
        data.end_time = dayjs(data.end_time).format('YYYY-MM-DD HH:mm:ss')
    }
    if (data.start_time >= data.end_time) {
        ElMessage.warning('开始时间不能大于等于结束时间')
        return
    }

    const start_hour = parseInt(data.start_time.split(' ')[1].split(':')[0])
    const end_hour = parseInt(data.end_time.split(' ')[1].split(':')[0])
    for (let hour = start_hour; hour < end_hour; hour++) {
        const key = `${hour}-${hour+1}-${data.venue_id}`
        if(reservationMap.value.has(key)) {
            const id = reservationMap.value.get(key)
            data.rez_ids.push(id)
        }
    }

    await createMaintenance(data)
    showAddDialog.value = false
    ElMessage.success('添加成功')
    // 重置表单
    addForm.value = { venue_id: 0, start_time: '', end_time: '', reason: '' }
}

// 获取预约记录
const FindReservation = async (date) => {
    const res = await apiFindReservation({
        page: 1,
        pageSize: 100,
        start_time: dayjs(date).format('YYYY-MM-DD'),
        end_time: dayjs(date).add(1, "day").format('YYYY-MM-DD'),
        status: 2
    })

    reservationList.value = res.data.reservations || [];
    reservationMap.value = new Map();

    reservationList.value.forEach((rez) => {
        const key = `${dayjs(rez.start_time).hour()}-${dayjs(rez.end_time).hour()}-${rez.venue_id}`;
        reservationMap.value.set(key, rez.id);
    });
    // console.log(reservationList.value);
    console.log(reservationMap.value);
}


// 重置筛选
const resetMaintenanceQuery = () => {
    maintenanceQuery.value = { venue_type_id: 1, start_time: '', end_time: '', reason: '' }
    fetchMaintenances(1)
}
// 只允许选择7~23点的整点
const disabledHours = () => {
    // 禁用0~6点和24点
    const disabled = []
    for (let i = 0; i < 24; i++) {
        if (i < 7 || i > 23) disabled.push(i)
    }
    return disabled
}
const disabledMinutes = () => {
    // 只允许选择0分
    const disabled = []
    for (let i = 1; i < 60; i++) {
        disabled.push(i)
    }
    return disabled
}
const disabledSeconds = () => {
    // 只允许选择0秒
    const disabled = []
    for (let i = 1; i < 60; i++) {
        disabled.push(i)
    }
    return disabled
}

////////////////////////////////////
// 显示编辑维护记录的flag
const showEditDialog = ref(false)

// 编辑表单
const editForm = ref({
    id: 0,
    venue_id: 0,
    start_time: '',
    end_time: '',
    reason: ''
})

// 编辑维护记录
const handleEdit = (row) => {
    editForm.value = {
        id: row.id,
        venue_id: row.venue_id,
        start_time: row.start_time,
        end_time: row.end_time,
        reason: row.reason
    }
    showEditDialog.value = true
}

// 更新维护记录
const handleUpdateMaintenance = async () => {
    if (!editForm.value.reason) {
        ElMessage.warning('请填写维护原因')
        return
    }
    
    try {
        await apiUpdateMaintenance({
            id: editForm.value.id,
            reason: editForm.value.reason
        })
        
        showEditDialog.value = false
        ElMessage.success('更新成功')
    } catch (error) {
        ElMessage.error('更新失败')
    }
}
// 编辑维护记录
const updateMaintenance = async (data) => {
    try {
        await apiUpdateMaintenance(data)
        await fetchMaintenances(currentPage.value)
    } catch (e) {
        throw e
    }
}


// 删除维护记录
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除这条维护记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await apiDeleteMaintenance(row.id)
            resetMaintenanceQuery()

            ElMessage.success('删除成功')
        } catch (error) {
            ElMessage.error('删除失败')
        }
    }).catch(() => {
        // 取消删除操作
    })
}

</script>

<style scoped src="@/assets/css/maintain.css"></style>